<?php

namespace App\Http\Controllers\Api\V1\Base;

use App\Http\Controllers\Api\V1\BaseController;
use App\Models\Base\Member;
use App\Models\Base\SendSms;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Log;
use Illuminate\Support\Facades\Validator;

class LoginController extends BaseController
{

    /**
     * @api {post} /login 登录
     * @apiDescription 登录
     * @apiGroup login
     * @apiPermission JWT
     * @apiVersion 0.1.0
     * @apiParam {Number} [phone] phone
     * @apiParam {String} [password] password
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *     {
     *        "id": 1
     *      "state":1
     *     }
     *   *@apiErrorExample {json} Error-Response:
     * HTTP/1.1 401
     *{
     * "message": "phone or password is incorrect",
     * "status_code": 401,
     * }
     */
    public function index(Request $request)
    {
        $validator = \Validator::make($request->input(), [
            'phone' => 'required|numeric',
            'password' => 'required'
        ]);

        if ($validator->fails()) {
            return $this->errorBadRequest($validator);
        }

        $attributes = $request->only('phone', 'password');

        // 验证失败返回403
        if (!$token = \Auth::attempt($attributes)) {
//        if (!$token = \Auth::attempt($credentials)) {
            $this->response->errorUnauthorized(trans('auth.incorrect'));
        }
        /*
            $phone=$attributes['phone'];
            $password=$attributes['password'];

            $users = Member::where(["phone"=>$phone])->first();

            $token = Auth::login($users);*/

//		//查询数据库中用户名及密码
//		if (!$token = Auth::login($users)) {
//			$this->response->errorForbidden(trans('auth.incorrect'));
//		}
        $users = Member::where("phone", $attributes['phone'])->first();

        Log::info($users);
        $result['data'] = [
            'token' => $token,
            'phone' => 1,
            'status' => $users->audit,
            'expired_at' => Carbon::now()->addMinutes(config('jwt.ttl'))->toDateTimeString(),
            'refresh_expired_at' => Carbon::now()->addMinutes(config('jwt.refresh_ttl'))->toDateTimeString(),
        ];

        return $this->response->array($result)->setStatusCode(201);

    }

    /**
     * @api {post} /phone  绑定手机
     * @apiDescription 绑定手机
     * @apiGroup login
     * @apiVersion 0.1.0
     * @apiParam {Number} phone 电话号码
     * @apiParam {Number} code 验证码
     * @apiParam {number} type 短信类型 1：绑定手机号
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *   {
     *       "status_code": 200
     *       "message": "绑定成功"
     *   }
     */
    public function phone(Request $request)
    {
        $validator = Validator::make($request->input(), [
            'phone' => 'required|numeric',
            'code' => 'required|numeric',
            'type' => 'required|numeric'
        ]);

        if ($validator->fails()) {
            return $this->errorBadRequest($validator);
        }

        $phone = $request->get('phone');
        $code = $request->get('code');
        //        return $phone;
        $sms = SendSms::where([
            'phone' => $phone,
            'code' => $code,
            'type' => $request->input('type'),
            'status' => 1
        ])->orderBy('id', 'desc')->first();

        if (!$sms) {
            return $this->response->errorNotFound("未发送短信");
        }
        //检查时间，状态是否正确 此处需修改为实际秒数
        $current = time() - 60;

        if ($sms->send_time < $current) {
            $sms->status = 2;
            $sms->save();
            return $this->response->errorForbidden("短信已过期");
        }
        $sms->status = 3;
        $sms->save();

        Member::where([
            'id' => $this->user->id
        ])->update([
            'phone' => $phone,
            'isrule' => 1
        ]);

        return $this->response->array([
            'status_code' => 200,
            'message' => '绑定成功',
        ])->setStatusCode(200);
    }

    /**
     * @api {post} /code 发送验证码(code)
     * @apiDescription 验证码(code)
     * @apiGroup login
     * @apiVersion 0.1.0
     * @apiParam {number} type 短信类型 1：绑定手机号
     * @apiParam {number} phone 手机号 正则表达式：/^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/
     * @apiSuccessExample {json} Success-Response:
     *  HTTP/1.1 200 OK
     *   {
     *       "status_code": 200,
     *       "message": "发送成功！"
     *   }
     */
    public function code(Request $request)
    {
        $validator = Validator::make($request->input(), [
            'type' => 'required|numeric',
            'phone' => [
                'required',
                'numeric',
                'regex:/^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/'
            ]
        ]);
        if ($validator->fails()) {
            return $this->errorBadRequest($validator);
        }

        $attributes = $request->only('phone');
        $phone = $attributes['phone'];

        $oldSms = SendSms::where([
            'phone' => $phone,
            'type' => $request->input('type'),
        ])->orderBy('created_at', 'DESC')->first();

        if ($oldSms)//60s 以内无重复，重复10次不再发出，返回错误
        {
            $createTime = strtotime($oldSms->created_at);
//            return $createTime;
            if ((time() - $createTime) <= 60) {
                $message = '重复发送';
                return $this->response->errorForbidden($message);
            }
        }

        if (env('APP_ENV') != 'local') {
            $code = mt_rand(1000, 9999);
            $content = '【小蟹集步兑】验证码为：' . $code;
            $result = \sendSms($phone, $content);
        } else {
            $code = 1234;
            $content = $code;
            $result = true;
        }

        if ($result) {
            $sms = new SendSms();
            $sms->phone = $phone;
            $sms->code = $code;
            $sms->content = $content;
            $sms->type = $request->input('type');
            $sms->status = 1;
            $sms->send_time = time();
            $sms->save();
            return $this->response->array([
                'status_code' => 200,
                'message' => '发送成功！'
            ])->setStatusCode(200);

        } else {
            return $this->response->errorForbidden("验证码发送失败");
        }
    }

}
